<template>
	<CustomNavBarVue title="抬头编辑"/>
	<view class="container">
		<view class="form-section">
			<view class="form-item">
				<text class="label required">抬头类型</text>
				<view class="radio-group">
					<view :class="['radio-item', { active: title.type === 'company' }]" @click="title.type = 'company'">
						<uni-icons :type="title.type === 'company' ? 'checkbox-filled' : 'circle'" :color="title.type === 'company' ? '#1DCFB7' : '#ccc'" size="22"></uni-icons>
						<text>非自然人</text>
					</view>
					<view :class="['radio-item', { active: title.type === 'personal' }]" @click="title.type = 'personal'">
						<uni-icons :type="title.type === 'personal' ? 'checkbox-filled' : 'circle'" :color="title.type === 'personal' ? '#1DCFB7' : '#ccc'" size="22"></uni-icons>
						<text>自然人</text>
					</view>
				</view>
			</view>
			<view class="border-line" />
			<!-- <DividerLineVue margin-right="-30rpx" width="180rpx" /> -->
			<view class="form-item">
				<text class="label required">抬头名称</text>
				<input class="input" v-model="title.name" placeholder="请输入抬头名称" />
			</view>
			<view class="border-line" />
			<view class="form-item" v-if="title.type === 'company'">
				<text class="label required">税号</text>
				<input class="input" v-model="title.taxId" placeholder="请输入税号" />
			</view>
			<view class="border-line" />
			<!--
			<view class="form-item">
				<text class="label">地址</text>
				<input class="input" v-model="title.address" placeholder="请输入地址" />
			</view>
			-->
			<view class="form-item">
				<text class="label">电话</text>
				<input class="input" v-model="title.phone" placeholder="请输入联系方式" />
			</view>
			<view class="border-line" />
			<view class="form-item" v-if="title.type === 'company'">
				<text class="label">开户银行</text>
				<input class="input" v-model="title.bankName" placeholder="请输入开户银行" />
			</view>
			<view class="border-line" />
			<view class="form-item" v-if="title.type === 'company'">
				<text class="label">银行账号</text>
				<input class="input" v-model="title.bankAccount" placeholder="请输入银行账号" />
			</view>
			<view class="border-line" />

			<!-- 地址灰色矩形（银行账号下） -->
			<view class="extra-block">
				<text class="section-title">地址</text>
				<view class="gray-box">
					<textarea class="textarea" v-model="title.address" placeholder="请输入地址" auto-height></textarea>
				</view>
			</view>
			<!-- <view class="border-line" /> -->

			<!-- 智能粘贴灰色矩形（银行账号下） -->
			<!-- <view class="extra-block">
				<view class="smart-paste-header">
					<text class="section-title">智能粘贴</text>
					<text class="paste-action" @click="pasteFromClipboard">粘贴</text>
				</view>
				<view class="gray-box gray-box-paste">
					<textarea class="textarea" v-model="smartPasteText" auto-height></textarea>
					<view v-if="!smartPasteText" class="placeholder-center">粘贴文本到此处，将自动识别抬头信息</view>
				</view>
			</view> -->
		</view>

		<view class="form-section">
			<view class="form-item">
				<view class="default-wrap" @click="toggleDefault">
					<uni-icons :type="title.isDefault ? 'checkbox-filled' : 'circle'" :color="title.isDefault ? '#1DCFB7' : '#ccc'" size="28"></uni-icons>
					<text class="default-text">设置为默认抬头</text>
				</view>
			</view>
		</view>

		<view class="footer">
			<view class="footer-actions">
				<view class="delete-btn-wrap"><text class="delete-text" v-if="isEdit && title.id" @click="deleteCurrent">删除</text></view>
				<button class="save-btn" @click="saveTitle">保存</button>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import CustomNavBarVue from '@/components/CustomNavBar.vue';
import InvoiceApi from '@/api/app/invoice.js';
// import DividerLineVue from '@/components/DividerLine.vue';

const title = ref({
  id: null,
  type: 'company', // 'company' or 'personal'
  name: '',
  taxId: '',
  address: '',
  phone: '',
  bankName: '',
  bankAccount: '',
  email: '',
  isDefault: false
});

const isEdit = ref(false);
const smartPasteText = ref('');

// 将接口返回的抬头详情映射到编辑表单结构（兼容 bank_account 合并字段）
const mapHeadDetailToForm = (item = {}) => {
  // 处理开户行及账号的合并字段
  let bankNameFromMerged = '';
  let bankAccountFromMerged = '';
  const merged = (item.bankAccount ?? '').trim();
  if (merged) {
    // 尝试匹配："招商银行 6222..." 或 "招商银行(6222...)" / "招商银行（6222...）"
    const parenMatch = merged.match(/^(.+?)\s*(\d{16,19})$/);
    if (parenMatch) {
      bankNameFromMerged = (parenMatch[1] || '').trim();
      bankAccountFromMerged = (parenMatch[2] || '').trim();
    } else {
      const parts = merged.split(/\s+/);
      if (parts.length >= 2) {
        bankAccountFromMerged = parts.pop() || '';
        bankNameFromMerged = parts.join(' ');
      } else {
        bankNameFromMerged = merged;
      }
    }
  }

  return {
    id: item.id ?? item.headId ?? null,
    type: item.titleType === 1 ? 'company' : item.titleType === 0 ? 'personal' : (title.value.type || 'company'),
    name: item.headerName ?? item.name ?? '',
    taxId: item.taxNo ?? '',
    address: item.address ?? '',
    phone: item.phone ?? '',
    // 分离或直接使用返回的字段
    bankName: (bankNameFromMerged || item.bankName || ''),
    bankAccount: (bankAccountFromMerged || item.bankAccount || ''),
    email: item.email ?? '',
    isDefault: Boolean(item.isDefault)
  };
};

onLoad(async (options) => {
  const id = options?.id;
  if (id) {
    isEdit.value = true;

    // 优先接收列表页通过事件通道传递的详情数据
    try {
      const eventChannel = typeof getOpenerEventChannel === 'function' ? getOpenerEventChannel() : null;
      if (eventChannel) {
        eventChannel.on('initInvoiceTitle', (data) => {
          title.value = mapHeadDetailToForm(data);
        });
      }
    } catch (e) {
      // 忽略事件通道异常，走接口兜底
    }

    // 若事件通道未传或不可用，则回源接口获取详情
    if (!title.value.id) {
      try {
        uni.showLoading({ title: '加载中' });
        const res = await InvoiceApi.getInvoiceHeadDetail({ id });
        const detail = res?.data ?? res ?? {};
        title.value = mapHeadDetailToForm(detail);
      } catch (e) {
        console.error('编辑页获取抬头详情失败:', e);
        uni.showToast({ title: '详情加载失败', icon: 'none' });
      } finally {
        uni.hideLoading();
      }
    }
  }
});

const switchChange = async (e) => {
  const nextVal = !!e.detail.value;
  const prevVal = !!title.value.isDefault;

  // 当前为“是”尝试拨到“否”时拦截
  if (prevVal && !nextVal) {
    uni.showToast({ title: '必须设置一个默认抬头', icon: 'none' });
    // 阻止页面样式改变，将其变回「是」
    title.value.isDefault = true;
	e.detail.value = true;
    return;
  }

  // 拨到“是”：调用与列表页一致的设为默认接口
  if (nextVal) {
    if (!title.value.id) {
      uni.showToast({ title: '请先保存后再设置默认', icon: 'none' });
      title.value.isDefault = false;
      return;
    }
    try {
      uni.showLoading({ title: '设置中' });
      await InvoiceApi.updateInvoiceHeads({ id: title.value.id, isDefault: 1 });
      title.value.isDefault = true;
      uni.showToast({ title: '已设为默认抬头', icon: 'none' });
    } catch (err) {
      console.error('设置默认失败:', err);
      title.value.isDefault = prevVal;
      uni.showToast({ title: '设置默认失败', icon: 'none' });
    } finally {
      uni.hideLoading();
    }
  } else {
    // 非默认拨到“否”：保持为否
    title.value.isDefault = false;
  }
};

// 圆形勾选切换默认抬头
const toggleDefault = async () => {
  const prevVal = !!title.value.isDefault;
  const nextVal = !prevVal;

  if (prevVal && !nextVal) {
    uni.showToast({ title: '必须设置一个默认抬头', icon: 'none' });
    title.value.isDefault = true;
    return;
  }

  if (nextVal) {
    if (!title.value.id) {
      uni.showToast({ title: '请先保存后再设置默认', icon: 'none' });
      title.value.isDefault = false;
      return;
    }
    try {
      uni.showLoading({ title: '设置中' });
      await InvoiceApi.updateInvoiceHeads({ id: title.value.id, isDefault: 1 });
      title.value.isDefault = true;
      uni.showToast({ title: '已设为默认抬头', icon: 'none' });
    } catch (err) {
      console.error('设置默认失败:', err);
      title.value.isDefault = prevVal;
      uni.showToast({ title: '设置默认失败', icon: 'none' });
    } finally {
      uni.hideLoading();
    }
  }
};

// 从剪贴板粘贴到智能粘贴区域
const pasteFromClipboard = () => {
  if (typeof uni.getClipboardData === 'function') {
    uni.getClipboardData({
      success: (res) => {
        smartPasteText.value = res?.data || '';
        if (!smartPasteText.value) {
          uni.showToast({ title: '剪贴板为空', icon: 'none' });
        }
      },
      fail: () => {
        uni.showToast({ title: '读取剪贴板失败', icon: 'none' });
      }
    });
  } else {
    uni.showToast({ title: '当前平台暂不支持读取剪贴板', icon: 'none' });
  }
};

// 删除当前抬头
const deleteCurrent = () => {
  if (!title.value.id) return;
  uni.showModal({
    title: '提示',
    content: '确定要删除该抬头吗？删除后将无法使用该抬头开票',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '处理中' });
          await InvoiceApi.unbindInvoiceHeads({ id: title.value.id });
          uni.setStorageSync('invoiceTitleNeedsRefresh', '1');
          uni.$emit('invoiceTitleSaved', { id: title.value.id, isEdit: true, deleted: true });
          uni.showToast({ title: '已删除', icon: 'none' });
          setTimeout(() => {
            uni.navigateBack();
          }, 600);
        } catch (err) {
          console.error('删除失败:', err);
          uni.showToast({ title: '删除失败', icon: 'none' });
        } finally {
          uni.hideLoading();
        }
      }
    }
  });
};

const saveTitle = () => {
  // 必填校验：titleType、headerName；企业时 taxNo 必填
  const type = title.value.type;
  if (!type || (type !== 'company' && type !== 'personal')) {
    uni.showToast({ title: '请选择抬头类型', icon: 'none' });
    return;
  }
  if (!title.value.name) {
    uni.showToast({ title: '请输入抬头名称', icon: 'none' });
    return;
  }
  if (type === 'company' && !title.value.taxId) {
    uni.showToast({ title: '请输入税号', icon: 'none' });
    return;
  }

  const combineBankAccount = (bankName, bankAccount) => {
    const name = (bankName || '').trim();
    const acct = (bankAccount || '').trim();
    if (name && acct) return `${name} ${acct}`;
    return name || acct;
  };

  const payload = {
    headerName: title.value.name,
    titleType: type === 'company' ? 1 : 0,
    taxNo: type === 'company' ? title.value.taxId : '',
    address: title.value.address,
    phone: title.value.phone,
    bankAccount: combineBankAccount(title.value.bankName, title.value.bankAccount),
    email: title.value.email,
    isDefault: title.value.isDefault ? 1 : 0,
  };

  (async () => {
    try {
      uni.showLoading({ title: '保存中...' });
      if (isEdit.value && title.value.id) {
        await InvoiceApi.updateInvoiceHead({ id: title.value.id, ...payload });
      } else {
        const res = await InvoiceApi.createInvoiceHead(payload);
        const data = res?.data ?? res ?? {};
        title.value.id = data.id ?? title.value.id;
      }
      // 标记列表页需刷新，并广播保存事件
      uni.setStorageSync('invoiceTitleNeedsRefresh', '1');
      uni.$emit('invoiceTitleSaved', { id: title.value.id, isEdit: isEdit.value });
      uni.showToast({ title: '保存成功', icon: 'success' });
      setTimeout(() => {
        uni.navigateBack();
      }, 1200);
    } catch (e) {
      console.error('保存失败:', e);
      uni.showToast({ title: '保存失败', icon: 'none' });
    } finally {
      uni.hideLoading();
    }
  })();
};

</script>

<style scoped>
.container {
	/* background-color: #f5f5f5; */
	/* min-height: 100vh; */
}
.form-section {
	background-color: #fff;
	margin-top: 20rpx;
	padding: 0 30rpx;
}
.form-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx 0;
	/* position: relative; */
}
.form-item:last-child {
	/* 最后一项不显示分隔线 */
}
.form-item::after {
	content: '';
	position: absolute;
	left: 230rpx; /* 左侧不到头（30rpx 内边距 + 200rpx label宽度） */
	right: 0;
	bottom: 0;
	height: 1rpx;
	background-color: #eee;
}
.label {
	font-size: 30rpx;
	/* color: #333; */
	width: 200rpx;
	white-space: nowrap;
	color: #7A7A7C;
}
.label.required::before {
	content: '*';
	color: red;
	margin-right: 4rpx;
}
.input {
	flex: 1;
	text-align: right;
	font-size: 30rpx;
}
.checkbox-wrap { display: flex; align-items: center; }
.radio-group {
	display: flex;
	align-items: center;
}
.radio-item {
	display: flex;
	align-items: center;
	margin-right: 40rpx;
	font-size: 30rpx;
}
.radio-item text {
	margin-left: 10rpx;
}
.extra-block { margin-top: 35rpx; }
.section-title { 
	font-size: 30rpx; 
	color: #7A7A7C;
	/* color: #333;  */
}
/* .smart-paste-header { display: flex; justify-content: space-between; align-items: center; } */
/* .paste-action { color: #1DCFB7; font-size: 26rpx; } */
.gray-box { 
    background-color: #EFF1F5; 
    border-radius: 12rpx; 
    margin-top: 25rpx;
    position: relative;
    padding: 20rpx; /* 灰色矩形内边距，使文本上下左右距边 20rpx */
}
/* .gray-box-paste { position: relative; } */
/* .placeholder-center {
    position: absolute;
    top: 20rpx; left: 20rpx; right: 20rpx; bottom: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #7A7A7C;
    font-size: 28rpx;
    text-align: center;
    padding: 0 20rpx;
    pointer-events: none;
} */
.textarea { width: 100%; min-height: 160rpx; font-size: 28rpx; color: #7A7A7C; }
.footer {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 40rpx 30rpx;
}
.footer-actions { display: flex; justify-content: space-between; align-items: center; }
.delete-text { color: #7A7A7C; font-size: 30rpx; }
.save-btn {
	background-color: #1DCFB7;
	color: #fff;
	height: 88rpx;
	line-height: 88rpx;
	border-radius: 44rpx;
	font-size: 32rpx;
	flex: 1;
}
.delete-btn-wrap{
	margin: 20rpx 60rpx 20rpx 30rpx
}
.default-wrap { display: flex; align-items: center; }
.default-text { font-size: 30rpx; color: #7A7A7C; margin-left: 16rpx; }
/* 边框线 */
.border-line {
  height: 1px;
  background-color: #E9EBF3;
  margin: 0 -30rpx 0 0; 	/* 按需调整 */
}
</style>